/*
 * @Description: 
 * @Author: paddies
 * @Date: 2024-06-05 23:44:54
 * @LastEditors: paddies
 * @LastEditTime: 2024-06-06 01:29:57
 * @FilePath: /shared_components/lib/luntai-components/search-panel/controller.dart
 */
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shared_components/luntai-components/search-panel/state.dart';

class SearchPanelController extends GetxController {
  final SearchPanelState state = SearchPanelState();

  onRefresh({required Function searchAPICallback}) {
    state.pageNum.value = "0";
    state.total.value = 0;
    getList(searchAPICallback: searchAPICallback);
  }

  nextPage({required Function searchAPICallback}) {
    getList(searchAPICallback: searchAPICallback);
  }

  getList({required Function searchAPICallback}) async {
    var pageNum = int.parse(state.pageNum.value.toString());
    var pageSize = state.pageSize.value.toString();
    var total = state.total.value ?? 0;

    var nextPageNum = (pageNum + 1).toString();

    print('另外一页===');
    print(nextPageNum);

    if (total == 0) {
      state.list.value = [];
      nextPageNum = "1";
    } else {
      var maxIndex =
          (int.parse(total.toString()) / int.parse(pageSize)).ceilToDouble();
      if (int.parse(nextPageNum) > maxIndex) {
        EasyLoading.showInfo("没有更多数据了");
        return;
      }
    }

    var data =
        await searchAPICallback(state.searchKey.value, nextPageNum, pageSize);
    print("搜索板块返回值");
    print(data);
    if (nextPageNum == "1") {
      state.list.value = [];
    }
    state.list.value = state.list.value + data["rows"];
    state.total.value = data["total"];
    state.pageNum.value = nextPageNum;

    // searchAPI(
    //         key: state.searchKey.value,
    //         pageNum: nextPageNum,
    //         pageSize: pageSize)
    //     .then((data) {
    //   print("搜索板块返回值");
    //   print(data);
    //   if (nextPageNum == "1") {
    //     state.list.value = [];
    //   }
    //   state.list.value = state.list.value + data["rows"];
    //   state.total.value = data["total"];
    //   state.pageNum.value = nextPageNum;
    // });
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
  }
}
